package com.tangkun.environment.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tangkun.environment.R;
import com.tangkun.environment.utils.Utils;
import com.tangkun.environment.view.CustomViewPager;
import com.tangkun.environment.view.ZoomableImageView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author tangkun
 * @ClassName: ClassStarImageActivity
 * @Description: TODO(荣誉堂下的相册列表选中与不选中操作)
 * @date 2016年3月24日 下午2:08:52
 */
public class SelectImageActivity extends BaseActivity {
    private ImageAdapter adapter;
    private CustomViewPager pager;

    // 还能上传的图片张数
    private int num = 0;
    private List<String> urlList;
    private List<File> fileList;
    // 选中的图片id集合
    private Set<Integer> selectedSet = new HashSet<Integer>();
    ;
    private TextView headTitleTxt, selectedNumTv, doneTv;
    private ImageView headImg;
    private LinearLayout originalLL;
    private ImageView originalImg;
    private TextView originalTv;
    /**
     * 原图是否被选中
     */
    private boolean isOriginalSelected = false;
    private boolean isShowOriginal = false;
    private int index = 0;
    /**
     * 相册里有选中图片有变动返回码
     */
    public static int RESULT_CODE_SELECT_CHANGED = 5;

    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xiangce_select);
        num = getIntent().getIntExtra("num", 0);
        isOriginalSelected = getIntent().getBooleanExtra("isOriginalPic", false);
        urlList = (List<String>) getIntent().getSerializableExtra("urlList");
        fileList = (List<File>) getIntent().getSerializableExtra("fileList");
        index = (Integer) getIntent().getIntExtra("index", 0);
        selectedSet = (Set<Integer>) getIntent().getSerializableExtra("selectedSet");
        isShowOriginal = getIntent().getBooleanExtra("isShowOriginal", false);

        headTitleTxt = (TextView) findViewById(R.id.head_title);
        headTitleTxt.setText("相册(" + (index + 1) + "/" + urlList.size() + ")");
        headImg = (ImageView) findViewById(R.id.img);
        originalLL = (LinearLayout) findViewById(R.id.original_ll);
        originalImg = (ImageView) findViewById(R.id.original_img);
        originalTv = (TextView) findViewById(R.id.original_tv);
        selectedNumTv = (TextView) findViewById(R.id.selected_num_tv);
        initSelectedNum();
        doneTv = (TextView) findViewById(R.id.done_tv);

        if (selectedSet.contains(index)) {
            headImg.setImageResource(R.mipmap.ic_class_star_checked);
        } else {
            headImg.setImageResource(R.mipmap.ic_class_star_unchecked);
        }
        adapter = new ImageAdapter(urlList);
        pager = (CustomViewPager) findViewById(R.id.image);
        pager.setAdapter(adapter);
        pager.setCurrentItem(index);

        initOriginal();
        initListener();
        if (isShowOriginal) {//显示原图控件
            originalLL.setVisibility(View.VISIBLE);
        } else {//不显示原图控件
            originalLL.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化选中数量，有选中显示，没有选中隐藏
     */
    private void initSelectedNum() {
        selectedNumTv.setText("" + selectedSet.size());// initialize selected
        // num
        if (selectedSet.size() > 0) {
            selectedNumTv.setVisibility(View.VISIBLE);
        } else {
            selectedNumTv.setVisibility(View.GONE);
        }
    }

    /**
     * 历史记录下原图选中未选中
     */
    private void initOriginal() {
        if (isOriginalSelected) {
            originalImg.setImageResource(R.mipmap.ic_original_selected);
            ArrayList<File> selectFileList = new ArrayList<File>();
            for (Integer i : selectedSet) {
                try {
                    selectFileList.add(fileList.get(i));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            String originalSize = "";// 选中图片列表大小
            try {
                originalSize = Utils.getImgFileListSizes(selectFileList);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                originalSize = "0.00MB";
                e.printStackTrace();
            }
            originalTv.setText("原图(" + originalSize + ")");
        }
    }

    /**
     * 原图点击之后的逻辑
     */
    private void initOriginalClicked() {
        if (isOriginalSelected) {
            originalImg.setImageResource(R.mipmap.ic_original_selected);
            ArrayList<File> selectFileList = new ArrayList<File>();
            // 原图选中时如果这样图片没有被选中，则设置为选中，然后计算选中图片大小；原图选中时这张图片被选中了，就不做任何处理
            if (!selectedSet.contains(index)) {
                if (selectedSet.size() < num) {
                    selectedSet.add(index);
                    headImg.setImageResource(R.mipmap.ic_class_star_checked);
                } else {
                    showToast("已超过可选图片数量");
                }
            } else {
                //ignore
            }
            for (Integer i : selectedSet) {
                try {
                    selectFileList.add(fileList.get(i));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            String originalSize = "";// 选中图片列表大小
            try {
                originalSize = Utils.getImgFileListSizes(selectFileList);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                originalSize = "0.00KB";
                e.printStackTrace();
            }
            originalTv.setText("原图(" + originalSize + ")");
        }
    }

    private void initListener() {
        pager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                index = arg0;
                headTitleTxt.setText("相册(" + (index + 1) + "/" + urlList.size() + ")");

                if (selectedSet.contains(index)) {
                    headImg.setImageResource(R.mipmap.ic_class_star_checked);
                } else {
                    headImg.setImageResource(R.mipmap.ic_class_star_unchecked);
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });

        // final Button button = (Button) findViewById(R.id.button);
        // button.setOnClickListener(new View.OnClickListener() {
        //
        // @Override
        // public void onClick(View arg0) {
        // try {
        // DownloadAsyncTask task = new DownloadAsyncTask(button, new
        // File(Helper.getRootPath(), "/download/" + new
        // SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg"));
        // task.execute(new URL(urlList.get(pager.getCurrentItem())));
        // } catch (Exception e) {
        //
        // }
        // }
        // });

        // 返回键
        ((ImageView) findViewById(R.id.back)).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO 退出时会监听相册中选中的图片数据
                Intent intent = new Intent();
                intent.putExtra("newSelectedSet", (Serializable) selectedSet);
                if (isOriginalSelected) {
                    intent.putExtra("isOriginalPic", true);
                } else {
                    intent.putExtra("isOriginalPic", false);
                }
                intent.putExtra("isBackClicked", true);
                setResult(RESULT_CODE_SELECT_CHANGED, intent);
                finish();
            }
        });

        headImg.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (selectedSet.contains(index)) {
                    selectedSet.remove(index);
                    headImg.setImageResource(R.mipmap.ic_class_star_unchecked);
                } else {
                    if (selectedSet.size() < num) {
                        selectedSet.add(index);
                        headImg.setImageResource(R.mipmap.ic_class_star_checked);
                    } else {
                        showToast("已超过可选图片数量");
                    }
                }
                initOriginal();
                ScaleAnimation mScaleAnimationStart = new ScaleAnimation(0.8f, 1.15f, 0.8f, 1.15f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                mScaleAnimationStart.setDuration(300);

                final ScaleAnimation mScaleAnimationEnd = new ScaleAnimation(1.15f, 1.0f, 1.15f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                mScaleAnimationEnd.setDuration(200);
                mScaleAnimationStart.setAnimationListener(new AnimationListener() {

                    @Override
                    public void onAnimationStart(Animation animation) {
                        // TODO Auto-generated method stub
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                        // TODO Auto-generated method stub
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        // TODO Auto-generated method stub
                        selectedNumTv.startAnimation(mScaleAnimationEnd);
                    }
                });
                // 有选中项才执行动画，没有则不执行动画
                if (selectedSet.size() > 0) {
                    selectedNumTv.startAnimation(mScaleAnimationStart);
                } else {
                    // ignore
                }
                initSelectedNum();
            }
        });

        originalLL.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (isOriginalSelected) {
                    isOriginalSelected = false;
                    originalImg.setImageResource(R.mipmap.ic_original_unselected);
                    originalTv.setText("原图");
                } else {
                    isOriginalSelected = true;
                    initOriginalClicked();
                }
            }
        });

        doneTv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO 完成按钮监听事件
                Intent intent = new Intent();
                intent.putExtra("newSelectedSet", (Serializable) selectedSet);
                if (isOriginalSelected) {
                    intent.putExtra("isOriginalPic", true);
                } else {
                    intent.putExtra("isOriginalPic", false);
                }
                intent.putExtra("isBackClicked", false);
                setResult(RESULT_CODE_SELECT_CHANGED, intent);
                finish();
            }
        });
    }

    private class DownloadAsyncTask extends AsyncTask<URL, Integer, Void> {

        private Button button;
        private Context context;
        private File file;

        public DownloadAsyncTask(Button button, File file) {
            this.button = button;
            this.context = button.getContext();
            this.file = file;
        }

        @Override
        protected void onPreExecute() {
            button.setEnabled(false);
        }

        @Override
        protected Void doInBackground(URL... params) {
            URL url = params[0];

            try {
                URLConnection conn = url.openConnection();
                conn.connect();

                long fileSize = conn.getContentLength();
                if (fileSize <= 0) {
                    Toast.makeText(context, "无法获知图片大小", Toast.LENGTH_SHORT).show();
                    cancel(true);
                    return null;
                }
                InputStream is = conn.getInputStream();
                if (is == null) {
                    Toast.makeText(context, "图片下载失败", Toast.LENGTH_SHORT).show();
                    cancel(true);
                    return null;
                }

                if (file.getParentFile().exists() == false) {
                    file.getParentFile().mkdirs();
                }

                OutputStream os = new FileOutputStream(file);
                publishProgress(0);

                byte buf[] = new byte[1024];
                int readed = -1, readedTotal = 0;
                while ((readed = is.read(buf)) != -1) {
                    os.write(buf, 0, readed);

                    readedTotal += readed;
                    publishProgress((int) (100 * readedTotal / fileSize));
                }
                publishProgress(100);
                is.close();
                os.close();
            } catch (Exception e) {
                Toast.makeText(context, "图片下载失败", Toast.LENGTH_SHORT).show();
            }
            return null;
        }

        @Override
        protected void onCancelled(Void v) {
            button.setEnabled(true);
        }

        @Override
        protected void onPostExecute(Void v) {
            button.setEnabled(true);
            try {
                MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getPath(), file.getName(), "");

                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
            } catch (Exception e) {

            }
            Toast.makeText(context, "图片已下载", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
        }
    }

    public void setUrlList(List<String> urlList) {
        adapter.setUrlList(urlList);
        adapter.notifyDataSetChanged();
    }

    private class ImageAdapter extends PagerAdapter {

        public ImageAdapter(List<String> urlList) {
            this.urlList = urlList;
        }

        private List<String> urlList;

        public List<String> getUrlList() {
            return urlList;
        }

        public void setUrlList(List<String> urlList) {
            this.urlList = urlList;
        }

        @Override
        public int getCount() {
            return urlList == null ? 0 : urlList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object obj) {
            return view == (View) obj;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            View v = getLayoutInflater().inflate(R.layout.pic_list, null);
            final ZoomableImageView imageView = (ZoomableImageView) v.findViewById(R.id.imageView);
            Bitmap bitmap = null;
            try {
                bitmap = Utils.decodeFile(fileList.get(position).getPath());
            } catch (Exception e) {

            }
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap);
            }
            ((ViewPager) container).addView(v, 0);
            return v;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

    }

    @Override
    public void onBackPressed() {
        // TODO 系统back按键监听，退出时会监听相册中选中的图片数据,back键无需回到回到添加页面
        Intent intent = new Intent();
        intent.putExtra("newSelectedSet", (Serializable) selectedSet);
        if (isOriginalSelected) {
            intent.putExtra("isOriginalPic", true);
        } else {
            intent.putExtra("isOriginalPic", false);
        }
        intent.putExtra("isBackClicked", true);
        setResult(RESULT_CODE_SELECT_CHANGED, intent);
        finish();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        pager.removeAllViews();
    }

}
